package com.java.multipledatasource.ms;

import java.util.*;

/**
 * @author hu
 * @version 1.0
 * @date 2021/1/4 0004 上午 12:15
 * @description
 */
public class RemoveChar {

    public  static String remove(String str) {
        if (str != null && !"".equals(str)) {
            Map<Character, Integer> strMap = new HashMap<>(str.length() * 2);
            char[] chars = str.toCharArray();
            for (char aChar : chars) {
                if (strMap.get(aChar) != null) {
                    strMap.put(aChar, strMap.get(aChar) + 1);
                } else {
                    strMap.put(aChar,  1);
                }
            }

            List<Map.Entry<Character, Integer>> list = new ArrayList<>(strMap.entrySet());
            list.sort((o1, o2) -> {
                if(o1.getValue() > o2.getValue()){
                    return 1;
                }else if(o1.getValue().equals(o2.getValue())){
                    return 0;
                }else{
                    return -1;
                }
            });
            if ( list.size() == 1 || !list.get(list.size() - 1).getValue().equals(list.get(list.size() - 2).getValue())) {
              return  str.replaceAll(String.valueOf(list.get(list.size() - 1).getKey()), "");
            } else   {
                List<Character> characterList = new ArrayList<>(str.length() * 2);
                Integer count = list.get(list.size() -1 ).getValue();
                for (int i = list.size() - 1; i >= 0; i--){
                    if (list.get(i).getValue().equals(count)) {
                        characterList.add(list.get(i).getKey());
                    } else {
                        break;
                    }
                }
                for (Character character : characterList) {
                  str = str.replaceAll(String.valueOf(character), "");
                }
                return str;
            }

        }
        return  null;
    }

    public static void main(String[] args) {
        System.out.println(remove("1212"));
        System.out.println(remove("1111"));
        System.out.println(remove("12121"));


    }
}
